package com.pay.allmoney.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.pay.allmoney.dto.AliPayDTO;
import com.pay.allmoney.dto.AliPayRefundDTO;
import com.pay.allmoney.dto.AlipayConfig;
import com.pay.allmoney.service.AliPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
@RequestMapping("/alipay")
@Slf4j
public class PayController {

	@Autowired
	private AliPayService aliPayService;

	/**
	 * 支付(付款)
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/trade.page.pay",method = RequestMethod.POST)
	@ResponseBody
	public String tradePage(@ModelAttribute AliPayDTO aliPayDTO) throws Exception {
		//获得初始化的AlipayClient
		AlipayClient alipayClient = aliPayService.getAliPayClient();
		log.info(AlipayConfig.gatewayUrl+";"+AlipayConfig.app_id);
		//设置请求参数
		AlipayTradePagePayRequest alipayRequest = aliPayService.getAliPayRequest();

		log.info("out_trade_no:{},total_amount:{},subject:{},body:{}",aliPayDTO.getOut_trade_no(),aliPayDTO.getTotal_amount(),aliPayDTO.getSubject(),aliPayDTO.getBody());

		alipayRequest.setBizContent(JSONObject.toJSONString(aliPayDTO));
		//请求
		String result = alipayClient.pageExecute(alipayRequest).getBody();

		//输出
		return result;
	}

	/**
	 * 支付宝服务器同步通知页面
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/returnUrl",method = RequestMethod.GET)
	public String getReturnUrl(HttpServletRequest request,Model model) throws Exception {
		//获取支付宝GET过来反馈信息
		Map<String,String[]> requestParams = request.getParameterMap();
		log.info("requestParams:{}"+requestParams);
		Map<String, String> params = getMap(requestParams);

		boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
		log.info("request:{}"+request);
		//——请在这里编写您的程序（以下代码仅作参考）——
		if(signVerified) {
			//商户订单号
			String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

			//支付宝交易号
			String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

			//付款金额
			String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
			log.info("trade_no:{}"+trade_no+",out_trade_no:{}"+out_trade_no+",total_amount:{}"+total_amount);
			//out.println("trade_no:"+trade_no+"<br/>out_trade_no:"+out_trade_no+"<br/>total_amount:"+total_amount);
			model.addAttribute("trade_no",trade_no);
			model.addAttribute("out_trade_no",out_trade_no);
			model.addAttribute("total_amount",total_amount);
		}else {
			//out.println("验签失败");
			model.addAttribute("message","验签失败");
		}
		//——请在这里编写您的程序（以上代码仅作参考）——
		return "return_url";
	}

	/**
	 * 重构
	 * @param requestParams
	 * @return
	 * @throws Exception
	 */
	private Map<String,String> getMap(Map<String,String[]> requestParams) throws Exception {
		Map<String,String> params = new HashMap<String,String>();
		log.info("requestParams:{}"+requestParams);
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用
			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		return params;
	}

	/**
	 * 获取支付宝POST过来反馈信息
	 * @return
	 */
	@RequestMapping(value = "/notifyUrl",method = RequestMethod.POST)
	public String getNotifyUrl(HttpServletRequest request,Model model) throws Exception {
		//获取支付宝POST过来反馈信息
		Map<String,String[]> requestParams = request.getParameterMap();
		log.info("requestParams:{}"+requestParams);
		Map<String, String> params = getMap(requestParams);

		boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
		log.info("signVerified:{}"+signVerified);
		//——请在这里编写您的程序（以下代码仅作参考）——

	/* 实际验证过程建议商户务必添加以下校验：
	1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
	2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
	3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
	4、验证app_id是否为该商户本身。
	*/
		if(signVerified) {//验证成功
			//商户订单号
			String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

			//支付宝交易号
			String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

			//交易状态
			String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
			log.info("out_trade_no:{}"+out_trade_no+",trade_no:{}"+trade_no+",trade_status:{}"+trade_status);
			if(trade_status.equals("TRADE_FINISHED")){
				//判断该笔订单是否在商户网站中已经做过处理
				//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
				//如果有做过处理，不执行商户的业务程序

				//注意：
				//退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
			}else if (trade_status.equals("TRADE_SUCCESS")){
				//判断该笔订单是否在商户网站中已经做过处理
				//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
				//如果有做过处理，不执行商户的业务程序

				//注意：
				//付款完成后，支付宝系统发送该交易状态通知
			}

			//out.println("success");
			model.addAttribute("message","success");

		}else {//验证失败
			//out.println("fail");
			model.addAttribute("message","fail");

			//调试用，写文本函数记录程序运行情况是否正常
			//String sWord = AlipaySignature.getSignCheckContentV1(params);
			//AlipayConfig.logResult(sWord);
		}

		//——请在这里编写您的程序（以上代码仅作参考）——
		return "notify_url";
	}

	@RequestMapping(value = "/trade.query",method = RequestMethod.POST)
	public String getTrade(@ModelAttribute AliPayDTO aliPayDTO, Model model) throws Exception {
		//获得初始化的AlipayClient
		AlipayClient alipayClient = aliPayService.getAliPayClient();

		//设置请求参数
		AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();

		//商户订单号，商户网站订单系统中唯一订单号
		//String out_trade_no = new String(request.getParameter("WIDTQout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
		//支付宝交易号
		//String trade_no = new String(request.getParameter("WIDTQtrade_no").getBytes("ISO-8859-1"),"UTF-8");
		//请二选一设置
		log.info("out_trade_no:{},trade_no:{}",aliPayDTO.getOut_trade_no(),aliPayDTO.getTrade_no());
		alipayRequest.setBizContent(JSONObject.toJSONString(aliPayDTO));

		//请求
		String result = alipayClient.execute(alipayRequest).getBody();
		Map map = (Map) JSONObject.parse(result);
		log.info("alipay_trade_query_response:{}",map.get("alipay_trade_query_response"));
		Map map1 = (Map) map.get("alipay_trade_query_response");
		model.addAttribute("buyer_user_id",map1.get("buyer_user_id"));
		model.addAttribute("out_trade_no",map1.get("out_trade_no"));
		model.addAttribute("total_amount",map1.get("total_amount"));
		model.addAttribute("trade_no",map1.get("trade_no"));
		model.addAttribute("buyer_logon_id",map1.get("buyer_logon_id"));
		return "pay_query";
	}

	/**
	 * 退款处理
	 * @param payRefundDTO
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/trade.refund",method = RequestMethod.POST)
	public String getRefund(@ModelAttribute AliPayRefundDTO payRefundDTO, Model model) throws Exception {
		//获得初始化的AlipayClient
		AlipayClient alipayClient = aliPayService.getAliPayClient();

		//设置请求参数
		AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();

		//商户订单号，商户网站订单系统中唯一订单号
		//String out_trade_no = new String(request.getParameter("WIDTRout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
		//支付宝交易号
		//String trade_no = new String(request.getParameter("WIDTRtrade_no").getBytes("ISO-8859-1"),"UTF-8");
		//请二选一设置
		//需要退款的金额，该金额不能大于订单金额，必填
		//String refund_amount = new String(request.getParameter("WIDTRrefund_amount").getBytes("ISO-8859-1"),"UTF-8");
		//退款的原因说明
		//String refund_reason = new String(request.getParameter("WIDTRrefund_reason").getBytes("ISO-8859-1"),"UTF-8");
		//标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
		//String out_request_no = new String(request.getParameter("WIDTRout_request_no").getBytes("ISO-8859-1"),"UTF-8");
		log.info("out_trade_no:{},trade_no:{},refund_amount:{},refund_reason:{},out_request_no:{}",payRefundDTO.getOut_trade_no(),payRefundDTO.getTrade_no(),payRefundDTO.getRefund_amount(),payRefundDTO.getRefund_reason(),payRefundDTO.getOut_request_no());

		alipayRequest.setBizContent(JSONObject.toJSONString(payRefundDTO));

		//请求
		String result = alipayClient.execute(alipayRequest).getBody();
		log.info("result:{}",result);
		Map map = (Map) JSONObject.parse(result);
		Map map1 = (Map)map.get("alipay_trade_refund_response");
		model.addAttribute("out_trade_no",map1.get("out_trade_no"));
		model.addAttribute("trade_no",map1.get("trade_no"));
		model.addAttribute("refund_fee",map1.get("refund_fee"));
		//输出
		return "refund";

	}

	@RequestMapping(value = "/refund.query",method = RequestMethod.POST)
	public String getRefundQuery(@ModelAttribute AliPayRefundDTO aliPayRefundDTO,Model model) throws Exception {
		//获得初始化的AlipayClient
		AlipayClient alipayClient = aliPayService.getAliPayClient();

		//设置请求参数
		AlipayTradeFastpayRefundQueryRequest alipayRequest = new AlipayTradeFastpayRefundQueryRequest();

		//商户订单号，商户网站订单系统中唯一订单号
		//String out_trade_no = new String(request.getParameter("WIDRQout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
		//支付宝交易号
		//String trade_no = new String(request.getParameter("WIDRQtrade_no").getBytes("ISO-8859-1"),"UTF-8");
		//请二选一设置
		//请求退款接口时，传入的退款请求号，如果在退款请求时未传入，则该值为创建交易时的外部交易号，必填
		//String out_request_no = new String(request.getParameter("WIDRQout_request_no").getBytes("ISO-8859-1"),"UTF-8");
		log.info("out_trade_no:{},trade_no:{},out_request_no:{}",aliPayRefundDTO.getOut_trade_no(),aliPayRefundDTO.getTrade_no(),aliPayRefundDTO.getOut_request_no());
		alipayRequest.setBizContent(JSONObject.toJSONString(aliPayRefundDTO));

		//请求
		String result = alipayClient.execute(alipayRequest).getBody();
		log.info("result:{}",result);
		Map map = (Map) JSONObject.parse(result);
		Map map1 = (Map)map.get("alipay_trade_fastpay_refund_query_response");
		model.addAttribute("out_trade_no",map1.get("out_trade_no"));
		model.addAttribute("total_amount",map1.get("total_amount"));
		model.addAttribute("refund_amount",map1.get("refund_amount"));
		model.addAttribute("trade_no",map1.get("trade_no"));

		//输出
		return "refund_query";
	}
}